<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="fileType" placeholder="请选择文件类型">
        <el-option
          v-for="item in fileTypes"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>
      <el-radio-group v-model="filters.fileDeleted" style="margin: 0 3px;">
        <el-radio-button :label="0" @click.native.prevent="fileDeletedFilter(0)">文件未删除</el-radio-button>
        <el-radio-button :label="1" @click.native.prevent="fileDeletedFilter(1)">文件已删除</el-radio-button>
      </el-radio-group>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleDeleteSelections">删除选中文件</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      border
      fit
      :height="tableHeight"
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="selsChange"
    >
      <el-table-column type="index" width="60" />
      <el-table-column type="selection" width="50" />
      <el-table-column prop="fileName" label="文件名" min-width="220" />
      <el-table-column prop="fileDeleted" label="文件删除状态" width="120" :formatter="formatDeleteStatus" />
      <el-table-column prop="length" label="文件大小" width="160" :formatter="formatLength" />
      <el-table-column label="操作" width="220" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="danger" size="small" @click="handleDelete(scope.index, scope.row)">删除文件</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="filters.page" :limit.sync="filters.limit" @pagination="loadPageList" />
  </div>
</template>

<script>
import { listFreeFiles, deleteFreeFiles, deleteMultiFreeFiles } from '@/api/free-files-api'
import waves from '@/directive/waves' // waves directive
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'FreeFiles',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableHeight: 260,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      sels: [], // 列表选中列
      filters: {
        page: 1,
        limit: 20,
        fileDeleted: 0
      },
      orderBy: {
        orderColumn: '',
        order: ''
      },
      fileType: 'clueCard',
      fileTypes: [{ value: 'app', label: '应用程序' }, { value: 'clueCard', label: '线索文件' },
        { value: 'movieAssist', label: '剧本手册' }, { value: 'movieCover', label: '剧本封面' },
        { value: 'movieScene', label: '剧本场景' }, { value: 'playRoleBook', label: '电子书' },
        { value: 'playRole', label: '玩家角色' }]
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'formLabelWidth', 'dynamicColumn'])
  },
  created() {
    this.tableHeight = window.innerHeight - 220
    this.loadPageList()
  },
  methods: {
    formatDeleteStatus(row) {
      if (row.fileDeleted) {
        return '已删除'
      }
      return '未删除'
    },
    formatLength(row) {
      let len = parseInt(row.length)
      if (len < 0) {
        return '未知'
      }
      const arr = ['B', 'K', 'M', 'G', 'T']
      let ret = ''
      for (let i = 0; i < arr.length; ++i) {
        ret = (len % 1024) + arr[i] + ret
        len = Math.floor(len / 1024)
        if (len <= 0) {
          break
        }
      }
      return ret
    },
    loadPageList() {
      this.listLoading = true
      listFreeFiles(this.fileType, this.filters).then(({ success, message, data }) => {
        this.listLoading = false
        if (success) {
          const { records = [], total } = data || {}
          records.forEach(item => { item.fileType = this.fileType })
          this.list = records
          this.total = total
        } else {
          this.$message({
            message: message || '查询列表失败',
            type: 'error'
          })
        }
      }, () => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.filters.page = 1
      this.loadPageList()
    },
    fileDeletedFilter(fileDeleted) {
      if (fileDeleted === this.filters.fileDeleted) {
        this.filters.fileDeleted = null
      } else {
        this.filters.fileDeleted = fileDeleted
      }
      this.handleFilter()
    },
    sortChange({ prop, order }) {
      this.orderBy.orderColumn = prop
      this.orderBy.order = order
      this.handleFilter()
    },
    selsChange(sels) {
      this.sels = sels
    },
    handleDelete(index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        deleteFreeFiles(row.fileType, row.id).then(({ success, message }) => {
          this.listLoading = false
          if (success) {
            this.$message({
              message: message || '删除成功',
              type: 'success'
            })
            this.loadPageList()
          } else {
            this.$message({
              message: message || '删除失败',
              type: 'error'
            })
          }
        }, (res) => {
          this.listLoading = false
        })
      }).catch(() => {

      })
    },
    handleDeleteSelections() {
      const cnt = this.sels.length
      if (cnt <= 0) {
        this.$message.warning('请选择要删除的文件')
        return
      }
      const sels = this.sels
      this.$confirm(`是否删除选中的${cnt}个文件?`, '提示', {
        type: 'warning'
      }).then(() => {
        console.log(`删除${cnt}个文件`)
        if (cnt > 0) {
          this.listLoading = true
          const arr = []
          for (let i = 0; i < cnt; ++i) {
            arr.push(new Promise((resolve, reject) => {
              deleteFreeFiles(sels[i].fileType, this.sels[i].id).then(({ success }) => {
                if (success) {
                  resolve(success)
                } else {
                  reject(false)
                }
              }, res => reject(false))
            }))
          }
          deleteMultiFreeFiles(arr).then(res => {
            this.listLoading = false
            const success = res.filter(item => item === true)
            this.$message({
              type: 'success',
              message: `成功删除${success.length}个文件,${res.length - success.length}个文件删除失败`
            })
            this.loadPageList()
          }, (message) => {
            this.listLoading = false
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
